package com.ht.api.task.ad;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ht.api.db.*;
import com.ht.api.db.task.HtTaskExecutor;
import com.ht.api.db.task.Plan;
import com.ht.api.db.task.TaskHandler;
import com.ht.api.open.OpenUtil;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 检查朋友圈客服发布状态
 */
@Slf4j
public class CheckMomentUserStatusTask implements TaskHandler  {

    /** 接口ID：获取客户朋友圈企业成员发表的列表*/
    protected static final long API_ID = 1900854229090832384L;

	@Override
	public String getName() {
		return "检查朋友圈客服发布状态";
	}

    @Override
    public boolean handler(JSONObject requestParam, String groupId, long taskId) {

        long tenantId = requestParam.getLong("tenant_id");
        DataSource ds = DbConfig.useTenantDb(tenantId);
        StreamLoadConfig config = DbConfig.useTenantSLC(tenantId);


        String adTaskGroupId = requestParam.getStr("ad_task_group_id");

        Entity adTaskGroup = Entity.create("ad_task_group");
        adTaskGroup.setMainId(adTaskGroupId);

        String momentId = requestParam.getStr("moment_id");
        String appid = requestParam.getStr("appid");

        JSONObject param = JSONUtil.createObj();
        param.set("moment_id", momentId);

        String str = OpenUtil.call(appid, API_ID, param);
        JSONObject result = JSONUtil.parseObj(str);

        List<Entity> dataList = new ArrayList<>();

        DbList momentUserList = Db.createSqlParser("wx_moment_user").where("ad_task_group_id", adTaskGroupId).where("publish_status", 0).query(ds);
        Set<String> users = new HashSet<>();
        for (Entity entity : momentUserList) {
            users.add(entity.getStr("userid"));
        }

        JSONArray taskList = result.getJSONArray("task_list");
        boolean isFinish = true;
        for (int i = 0; i < taskList.size(); i++) {
            JSONObject task = taskList.getJSONObject(i);
            String userid = task.getStr("userid");
            int publishStatus = task.getInt("publish_status");

            if (publishStatus == 0) {
                isFinish = false;
            } else {
                if (users.contains(userid)) {
                    adTaskGroup.set("status", 4);

                    Entity momentUser = Entity.create("wx_moment_user");
                    momentUser.set("ad_task_group_id", adTaskGroupId);
                    momentUser.set("userid", userid);
                    momentUser.set("publish_status", publishStatus);
                    momentUser.set("publish_time", DateUtil.now());
                    dataList.add(momentUser);


                    //查看客户可见范围
                    JSONObject pullMomentVisibleParam = JSONUtil.createObj();
                    pullMomentVisibleParam.set("appid", appid);
                    pullMomentVisibleParam.set("moment_id", momentId);
                    pullMomentVisibleParam.set("tenant_id", tenantId);
                    pullMomentVisibleParam.set("userid", userid);
                    pullMomentVisibleParam.set("ad_task_group_id", adTaskGroupId);
                    HtTaskExecutor.submitTask(pullMomentVisibleParam, new PullMomentVisibleTask(),
                            Plan.create().setMin(10).setTimes(2, TimeUnit.MINUTES));
                    log.info(userid + "客服已发表 success......");

                }

            }
        }

        Db.insertBatchWithStream(config, dataList);

        if (isFinish) {
            adTaskGroup.set("status", 5);
            HtTaskExecutor.stopTask(taskId);
        }

        Db.insert(ds, adTaskGroup);

        return true;
    }
}
